package com.example.productservice.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.productservice.entity.PageVO;
import com.example.productservice.entity.Product;
import com.example.productservice.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lenovo
 * @Description
 * @Date2025/4/14 下午4:38
 */
@RestController
public class ProductController {

    @Resource
    private ProductService productService;


    @RequestMapping("/product/{id}")
    @SentinelResource(value = "product/{id}",blockHandler = "findProductByIdExcpetion",blockHandlerClass = ExceptionHandler.class)
    public ResponseEntity<Product> findProductById(@PathVariable Integer id) {
//        int i=10/0;
        Product product = productService.getById(id);
        return ResponseEntity.ok(product);
    }


    @GetMapping("/products")
    public ResponseEntity<List<Product>> findAllProducts() {
        List<Product> list =productService.list();
        return ResponseEntity.ok(list);
    }


    @GetMapping("product-page")
    public ResponseEntity<PageVO> findProductsPage(@RequestParam(value = "current",required = false,defaultValue = "1") Integer current,
                                                   @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pagesize){
        Page<Product> page=productService.page(new Page<>(current,pagesize));
        PageVO pageVO=new PageVO(current,pagesize,page.getTotal(),page.getRecords());
        return ResponseEntity.ok(pageVO);
    }

    @PostMapping("/product")
    public ResponseEntity<String> addProduct(@RequestBody Product product) {
        productService.save(product);
        return ResponseEntity.ok("ok");
    }

    @PutMapping("/product")
    public ResponseEntity<String> updateProduct(@RequestBody Product product) {
        productService.updateById(product);
        return ResponseEntity.ok("ok");
    }

    @DeleteMapping("/product/{id}")
    public ResponseEntity<String> deleteProduct(@PathVariable Integer id) {
        productService.removeById(id);
        return ResponseEntity.ok("ok");
    }





//    public ResponseEntity<Product> findProductByIdExcpetion(Integer id, BlockException ex) {
//        Product product = new Product();
//        product.setName("这是被限流的商品数据");
//        return ResponseEntity.ok(product);
//    }
}
